<template>
  <vxe-modal
    v-model="dialogFormVisible"
    :title="title"
    show-footer
    transfer
    fullscreen
    destroy-on-close
    :loading="listLoading"
    @close="close"
  >
    <template #default>
      <vxe-grid
        ref="tableRef"
        border
        stripe
        keep-source
        auto-resize
        sync-resize
        height="auto"
        :loading="tableListLoading"
        :column-config="{ resizable: true }"
        :export-config="{}"
        :columns="tableColumn"
        align="center"
        :row-config="{ keyField: 'id', isCurrent: true, isHover: true }"
      >
        <template #form>
          <vxe-form
            ref="queryFormRef"
            :data="queryParams"
            title-align="right"
            title-width="120"
            prevent-submit
            custom-layout
          >
            <vxe-form-item title="数据源" field="dataSourceConfigId" span="12">
              <template #default>
                <el-select
                  v-model="queryParams.dataSourceConfigId"
                  class="!w-240px"
                  placeholder="请选择数据源"
                >
                  <el-option
                    v-for="config in dataSourceConfigList"
                    :key="config.id"
                    :label="config.name"
                    :value="config.id"
                  />
                </el-select>
              </template>
            </vxe-form-item>
            <vxe-form-item title="表名称" span="8" field="name">
              <template #default>
                <el-input
                  v-model="queryParams.name"
                  class="!w-240px"
                  clearable
                  placeholder="请输入表名称"
                  @keyup.enter="getList"
                />
              </template>
            </vxe-form-item>
            <vxe-form-item title="表描述" span="16" field="comment">
              <template #default>
                <el-input
                  v-model="queryParams.comment"
                  class="!w-240px"
                  clearable
                  placeholder="请输入表描述"
                  @keyup.enter="getList"
                />
              </template>
            </vxe-form-item>
            <vxe-form-item span="8">
              <template #default>
                <el-button plain @click="getList">
                  <i class="icon-wpkj-viewlarger" />
                  搜索
                </el-button>
              </template>
            </vxe-form-item>
            <vxe-form-item span="24">
              <template #default></template>
            </vxe-form-item>
          </vxe-form>
        </template>
      </vxe-grid>
    </template>
    <template #footer>
      <div class="dialog-footer" style="text-align: center">
        <el-button
          :loading="importTableLoading"
          type="primary"
          plain
          @click="handleImportTable"
        >
          <i class="icon-wpkj-falling" />
          导入
        </el-button>
        <el-button type="danger" plain @click="close">关闭</el-button>
      </div>
    </template>
  </vxe-modal>
</template>

<script>
  import * as CodegenApi from '@/api/infra/codegen'
  import * as DataSourceConfigApi from '@/api/infra/dataSourceConfig'

  export default defineComponent({
    name: 'ImportTable',
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')
      const $XEUtils = inject('$XEUtils')
      const state = reactive({
        queryFormRef: null,
        tableRef: null,
        tableListLoading: false,
        listLoading: false,
        subListLoading: false,
        importTableLoading: false,
        queryParams: {
          name: undefined,
          comment: undefined,
          dataSourceConfigId: 0,
        },
        selectRows: [],
        dataSourceConfigList: {},
        tableColumn: [
          { type: 'checkbox', width: 50, fixed: 'left' },
          {
            title: '表名称',
            field: 'name',
            width: 320,
          },
          {
            title: '表描述',
            field: 'comment',
            width: 360,
          },
        ],
        title: '',
        dialogFormVisible: false,
      })

      const open = async (row) => {
        state.dialogFormVisible = true
        state.title = '导入表'
        state.listLoading = true
        // 加载数据源的列表
        const { code, data, msg } =
          await DataSourceConfigApi.getDataSourceConfigList().catch((err) => {
            state.listLoading = false
          })
        state.listLoading = false
        state.dataSourceConfigList = data
      }

      const getList = async () => {
        state.tableListLoading = true
        const { code, data, msg } = await CodegenApi.getSchemaTableList(
          state.queryParams
        ).catch((err) => {
          state.tableListLoading = false
        })
        if (code === 0 || code === 200) {
          state['tableRef'].reloadData(data)
        } else {
          $baseMessage(msg, 'error', 'vab-hey-message-success')
        }
        state.tableListLoading = false
      }

      const handleImportTable = async () => {
        const rows = state['tableRef'].getCheckboxRecords()
        if (rows && rows.length > 0) {
          state.importTableLoading = true
          const { code, msg } = await CodegenApi.createCodegenList({
            dataSourceConfigId: state.queryParams.dataSourceConfigId,
            tableNames: $XEUtils.pluck(rows, 'name'),
          }).catch((err) => {
            state.importTableLoading = false
          })
          if (code !== 0 || code !== 200) {
            $baseMessage(msg, 'error', 'vab-hey-message-success')
          } else {
            emit('fetch-data')
            close()
          }
        } else {
          $baseMessage('未选中任何行', 'error', 'vab-hey-message-error')
        }
      }

      const setSelectRows = (val) => {
        state.selectRows = val
      }

      const close = () => {
        state['queryFormRef'].reset()
        state.queryParams = {
          name: undefined,
          comment: undefined,
          dataSourceConfigId: 0,
        }
        state.dataSourceConfigList = []
        state.dialogFormVisible = false
        state.listLoading = false
        state.subListLoading = false
        state.tableListLoading = false
        state.importTableLoading = false
      }

      onMounted(() => {})
      return {
        ...toRefs(state),
        open,
        close,
        getList,
        handleImportTable,
      }
    },
  })
</script>

<style lang="scss" scoped>
  .vab-tree-border {
    width: 100%;
    height: 250px;
    padding: $base-padding;
    overflow-y: auto;
    border: 1px solid #dcdfe6;
    border-radius: $base-border-radius;
  }

  .el-container {
    height: calc(100vh - 155px);
  }
</style>
